<?php

class MediaController extends Controller
{
	public $layout = 'main';

	public function actionIndex()
	{
		$intPage 		= (int)Yii::app()->request->getParam('page', 1);
		$intRowsPerPage = (int)Yii::app()->request->getParam('rpp', MIN_ROWS_PER_PAGE);
		$intSortType 	= Yii::app()->request->getParam('sort',-1);
		
		$strKeyword		= Yii::app()->request->getParam('keyword', null);
		$strFileTypes	= Yii::app()->request->getParam('filetype', null);
		$strGroupLabel  = Yii::app()->request->getParam('label', null);
		
		if($strFileTypes == 'image'){
			$strFileTypes = "jpg, jpeg, png, gif";
		}
		if($strFileTypes == 'video'){
			$strFileTypes = "flv, mp4, ogg, ogv, avi, mpeg, mov, wmv, mkv, 3gp";
		}
		
		$arrMedia = Media::getInstance()->getList(array('sort'=>$intSortType, 'keyword'=>$strKeyword, 'file_type'=>$strFileTypes, 'label'=>$strGroupLabel), $intPage, $intRowsPerPage);
		$intTotalRows = isset($arrMedia[0]['total_rows'])?$arrMedia[0]['total_rows']:0;
		
		//pagination
		$objPages=new CPagination($intTotalRows);
		$objPages->setCurrentPage($intPage-1);
		$objPages->setPageSize($intRowsPerPage);
		
		if(Yii::app()->request->isAjaxRequest && Yii::app()->request->isPostRequest){
			$strMessage = '';
			$pagination = array(
				'pageSize' => $objPages->getPageSize() /*rpp*/,
				'pageCount' => $objPages->getPageCount() /*total pages*/,			
				'currentPage' => $objPages->getCurrentPage(),
				'pageRange' => 5,
				'itemCount' => $objPages->getItemCount() /*total items*/
			);
			echo json_encode(array('list'=>$arrMedia, 'pagination'=>$pagination, 'message'=>$strMessage)); die;
		}
		$this->render('index', array(
			'arrMedia' => $arrMedia,
			'objPages' => $objPages
		));
	}
	
	public function actionPopup()
	{
		$this->renderPartial('popup', array());
	}
	
	public function actionForm(){
		$this->render('form', array(
		));
	}
	
	public function actionUpload(){
		$redirect = Yii::app()->request->getParam('redirect', 1);
		if(Yii::app()->request->isPostRequest){
			try{
				
				require_once('PHPThumb/PHPThumb.php');
				require_once('PHPThumb/GD.php');
				
				$strGroupLabel = Yii::app()->request->getParam('label', null);
				
				//Rearrange uploaded files
				$arrUploadedFiles = FileTransfer::rearrangeGlobalFilesArray();
				foreach($arrUploadedFiles as $name => $files){
					/*skip irrelevant name*/
					if($name != 'media') continue;
					foreach($files as $file)
					{
						/*skip no uploaded file error*/
						if($file['error'] == UPLOAD_ERR_NO_FILE) continue;
						/*start uploading...*/
						$objFileTransfer = new FileTransfer(UPLOADS_DIR, 'src/'.date('Y').'/'.date('md'));
						$objFileTransfer->setAllowedFileExts('jpg;jpeg;png;gif;swf;flv;mp4');
						$arrFileInfo = $objFileTransfer->upload($file);
						if($arrFileInfo !== false){
							/*prepare data for inserting db*/
							$args = array(
								'media_title' => $arrFileInfo['filename'],
								'media_file' => $arrFileInfo['path'],
								'media_file_size' => $arrFileInfo['size'],
								'media_file_extension' => $arrFileInfo['extension'],
								'media_status' => 0,
								'media_group_label' => $strGroupLabel
							);
							/*insert into database*/				
							$intResult = Media::getInstance()->insert($args);
							/*create thumbs if this is an image*/
							if($intResult > 0){
								if(!empty($arrFileInfo['extension']) && in_array($arrFileInfo['extension'], array('jpg', 'jpeg', 'png', 'gif'))){
									$strFilePath = UPLOADS_DIR.'/'.$arrFileInfo['path'];
									$strThumbPath = str_replace('/src/', '/thumbs/75x75/', $strFilePath);
									@mkdir(pathinfo($strThumbPath, PATHINFO_DIRNAME), 0, true);								
									$thumb = new PHPThumb\GD($strFilePath);
									$thumb->resize(75, 75);
									$thumb->save($strThumbPath);
								}
							}
						}
					}
				}
			} catch(Exception $ex) {
				o($ex->getMessage());
				//$this->_helper->getHelper('FlashMessenger')->addMessage(json_encode(array('type'=>'error', 'msg'=>$ex->getMessage())));
			}
		}
		/*TODO: redirect to finished page*/
		/*if($redirect){
			header('Location: '.LINK_ADMINCP_MEDIA.'/form'); die;
			//$this->_redirect(LINK_ADMINCP_MEDIA);
		}*/
		if(Yii::app()->request->isAjaxRequest && Yii::app()->request->isPostRequest){
			echo $intResult;
		}
		header('Location: '.LINK_ADMINCP_MEDIA.'/form'); die;
	}

	public function actionDownload(){
		$strGroupLabel = Yii::app()->request->getParam('label', null);
		$url = Yii::app()->request->getParam('url', null);
		if (filter_var($url, FILTER_VALIDATE_URL) === false) {
			die("{$url} is not a valid URL");
		}
		
		if(Yii::app()->request->isPostRequest){
			
			
			$objFileTransfer = new FileTransfer(UPLOADS_DIR, 'src/'.date('Y').'/'.date('md'));
			$objFileTransfer->setAllowedFileExts('jpg;jpeg;png;gif;swf;flv;mp4');
			$arrFileInfo = $objFileTransfer->downloadFromUrl($url);
			
			if($arrFileInfo !== false){
				/*prepare data for inserting db*/
				$args = array(
					'media_title' => $arrFileInfo['filename'],
					'media_file' => $arrFileInfo['path'],
					'media_file_size' => $arrFileInfo['size'],
					'media_file_extension' => $arrFileInfo['extension'],
					'media_status' => 0,
					'media_group_label' => $strGroupLabel
				);
				/*insert into database*/				
				$intResult = Media::getInstance()->insert($args);
				/*create thumbs if this is an image*/
				if($intResult > 0){
					if(!empty($arrFileInfo['extension']) && in_array($arrFileInfo['extension'], array('jpg', 'jpeg', 'png', 'gif'))){
						$strFilePath = UPLOADS_DIR.'/'.$arrFileInfo['path'];
						$strThumbPath = str_replace('/src/', '/thumbs/75x75/', $strFilePath);
						@mkdir(pathinfo($strThumbPath, PATHINFO_DIRNAME), 0, true);								
						$thumb = new PHPThumb\GD($strFilePath);
						$thumb->resize(75, 75);
						$thumb->save($strThumbPath);
					}
				}
			}
		}
		if(Yii::app()->request->isAjaxRequest && Yii::app()->request->isPostRequest){
			echo $intResult;
		}
		header('Location: '.LINK_ADMINCP_MEDIA.'/form'); die;
	}
}